// pages/mymessage/mymessage.js
import Dialog from '../../dist/dialog/dialog';
const timeFormatting = require('../../utils/timeFormatting.js');
const util = require('../../utils/util.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    changeList: [],
    checkList: [],
    systemList: [],
    flag: {
      change: 0,
      check: 0,
      system: 0
    },
    pageNumber: 1,
    pageSize: 20,
    totalPages: 1,
    sortOrder: "asc",
    user: {},
    msgType: 1,
    applyMessage: 0,
    changeMessage: 0,
    systemMessage: 0,
    applyMessages: '',
    changeMessages: '',
    systemMessages: '',
    isOpen:false,
    openText:"展开",
    status:null,
  },

  openViewClick: function (e) {
    var id = e.currentTarget.dataset.id
    // console.log("点击111111", id)
    if (!this.data.changeList[id].messagestatus) {
      this.toggle("changeList[" + id + "].messagestatus", true);
    } else {
      this.toggle("changeList[" + id + "].messagestatus", false);
    }
  },

  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  onChange: function(event) {
    this.setData({
      status:null,
      active: event.detail.index,
      pageNumber: 1,
      msgType: event.detail.index + 1
    })
    console.log("msgType", this.data.msgType)
    this.getList(false);
  },
  getInfo: function() {
    var that = this;
    app.req({
      url: "wechat/sysMessage/getMessageType",
      method: "post",
      data: {},
      success: function(res) {
        if (200 == res.code) {
          console.log("返回未读条数",res)
          var data = res.data;
          that.setData({
            changeMessages: data.changeMessage,
            applyMessages: data.applyMessage,
            systemMessages: data.systemMessage
          })
          console.log("状态为", that.data.systemMessages)
          that.toggle("flag.change", data.changeMessage * 1);
          that.toggle("flag.check", data.applyMessage * 1);
          that.toggle("flag.system", data.systemMessage * 1);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  getList: function(append) {
    var that = this;
    this.getInfo();
    if (!append){
      this.toggle("changeList", []);
      this.toggle("checkList", []);
      this.toggle("systemList", []);
    }
    switch (that.data.active) {
      case 0:
        that.getDataList(append, 'changeList');
        break;
      case 1:
        that.getDataList(append, 'checkList');
        break;
      case 2:
        that.getDataList(append, 'systemList');
        break;
    }
  },
  getDataList: function(append, key) {
    var that = this;
    var data = that.data;
    app.req({
      url: "wechat/sysMessage/list",
      method: "post",
      data: {
        pageNumber: data.pageNumber,
        sortOrder: data.sortOrder,
        pageSize: data.pageSize,
        msgType: data.msgType
      },
      success: function(res) {
        if (200 == res.code) {
          console.log("时间", res)
          var list = that.data[key];
          var nowList = res.data.rows;
          for (var i in nowList) {
            var item = nowList[i];
            if (item.createTime) {
              var time = new Date((item.createTime).replace(/-/g, "/")).getTime();
              item.createTime = timeFormatting.showDate(new Date(time))
            }
          }
          console.log(append)
          if (append) {
            that.setData({
              [key]: list.concat(nowList),
              totalPages: res.data.totalPages
            });
          } else {
            that.setData({
              [key]: nowList,
              totalPages: res.data.totalPages
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  setRead: function(event) {
    var that = this;
    var dataset = event.currentTarget.dataset;
    var id = dataset.id;
    var read = dataset.read;
    var content = dataset.content;
    var msgType = dataset.msgtype
    console.log(event)
    // Dialog.alert({
    //   message: content
    // }).then(() => {
    //   if (!read) {
    //     that.setReadRequest(dataset);
    //   }
    // });
    if (!read) {
      that.setReadRequest(dataset);
    }
    if (msgType == 32 || msgType == 33){
      wx.navigateTo({
        url: '/pages/partySettingMemo/partySettingMemo?id=' + dataset.activityid
      });
    } else if (msgType == 25){
      wx.navigateTo({
        url: '/pages/transactionRecord/transactionRecord'
      });
    } else if (msgType == 52){
      wx.navigateTo({
        url: '/pages/transactionRecord/transactionRecord'
      });
    } 
    // else if (msgType == 36 || msgType == 35 || msgType == 37 || msgType == 45 || msgType == 46 || msgType == 47){
    //   wx.navigateToMiniProgram({
    //     appId: 'wxa0535d31b27c14d8',
    //     path: 'pages/orgDetails/orgDetails?id=' + dataset.activityid,
    //     envVersion: 'trial',
    //   })
    // } else if (msgType == 44){
    //   wx.navigateToMiniProgram({
    //     appId: 'wxa0535d31b27c14d8',
    //     path: 'pages/memberList/memberList?id=' + dataset.activityid,
    //     envVersion: 'trial',
    //   })
    // }
    else{
      wx.navigateTo({
        url: '/pages/register/register?id=' + dataset.activityid
      });
    }
  },
  setReadRequest: function(dataset) {
    console.log('dataset', dataset)
    var that = this;
    app.req({
      url: "wechat/sysMessage/update",
      method: "post",
      data: {
        id: dataset.id
      },
      success: function(res) {
        if (200 == res.code) {
          console.log("修改阅读状态",res)
          var index = dataset.index;
          var data = that.data;
          var flag = data.flag;
          switch (data.active * 1) {
            case 0:
              that.setData({
                changeMessages: that.data.changeMessages-1,
              })
              that.toggle("flag.change", flag.change - 1);
              that.toggle("changeList[" + index + "].isRead", 1);
              break;
            case 1:
              that.setData({
                applyMessages: that.data.applyMessages - 1,
              })
              that.toggle("flag.check", flag.check - 1);
              that.toggle("checkList[" + index + "].isRead", 1);
              break;
            case 2:
              that.setData({
                systemMessages: that.data.systemMessages - 1,
              })
              that.toggle("flag.system", flag.system - 1);
              that.toggle("systemList[" + index + "].isRead", 1);
              break;
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  setCheck: function(event) {
    var that = this;
    var dataset = event.currentTarget.dataset;
    var userName = dataset.user;
    if (dataset.msgtype == 8 || dataset.msgtype == 9) {
      this.setRead(event);
    } 
    if (dataset.msgtype == 7 || dataset.msgtype == 38){
      console.log('审核')
      wx.navigateTo({
        url: '/pages/enlistManage2/enlistManage2?id=' + dataset.activityid
      });
      var arry = []
      arry.push(dataset.id)
      app.req({
        url: "wechat/sysMessage/update",
        method: "post",
        data: {
          ids: arry
        },
        success: function (res) {
          if (200 == res.code) {
            that.getInfo()
            var index = dataset.index;
            var data = that.data;
            var flag = data.flag;
            that.toggle("flag.check", flag.check - 1);
            that.toggle("checkList[" + index + "].isRead", 1);
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
      // if (!dataset.check) {
      //   Dialog.confirm({
      //     message: userName + "能够通过审核?",
      //     cancelButtonText: '不通过'
      //   }).then(() => {
      //     that.setCheckRequest(dataset, 1);
      //   }).catch(() => {
      //     that.setCheckRequest(dataset, 2);
      //   });
      // }
    } else if (dataset.msgtype == 27 || dataset.msgtype == 26){
      wx.navigateTo({
       url: '/pages/register/register?id=' + dataset.activityid
      });
      var arry = []
      arry.push(dataset.id)
      app.req({
        url: "wechat/sysMessage/update",
        method: "post",
        data: {
          ids: arry
        },
        success: function (res) {
          if (200 == res.code) {
            that.getInfo()
            var index = dataset.index;
            var data = that.data;
            var flag = data.flag;
            that.toggle("flag.check", flag.check - 1);
            that.toggle("checkList[" + index + "].isRead", 1);
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }

  },
  setCheckRequest: function(dataset, type) {
    var that = this;
    app.req({
      url: "wechat/activity/review",
      method: "post",
      data: {
        activityId: dataset.activityId,
        msgId: dataset.id,
        type: type
      },
      success: function(res) {
        if (200 == res.code) {
          var index = dataset.index;
          var data = that.data;
          var flag = data.flag;
          that.setData({
            applyMessages: that.data.applyMessages - 1,
          })
          that.toggle("flag.check", flag.check - 1);
          that.toggle("checkList[" + index + "].isRead", 1);
        } else {
          var index = dataset.index;
          var data = that.data;
          var flag = data.flag;
          that.setData({
            applyMessages: that.data.applyMessages - 1,
          })
          that.toggle("flag.check", flag.check - 1);
          that.toggle("checkList[" + index + "].isRead", 1);
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },

  //变更消息全读
  readAllBindtap:function () {
    var that = this;
    app.req({
      url: "wechat/sysMessage/updateByType",
      method: "post",
      data: {
        type:0
      },
      success: function (res) {
        if (200 == res.code) {
          that.getInfo()
          that.getList(false);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  delAllBindtap: function () {
    var that = this;
    var type = ''
    if (that.data.active == 0) {
      type = 0
    } else if (that.data.active == 1) {
      type = 2
    } else if (that.data.active == 2) {
      type = 1
    }
    wx.showModal({
      content: '是否确认删除',
      cancelText: '再想想',
      cancelColor: '#999999',
      confirmColor: '#2168EB',
      success(res) {
        if (res.confirm) {
          app.req({
            url: "wechat/sysMessage/actUpdateDelByType",
            method: "post",
            data: {
              type: type
            },
            success: function (res) {
              if (200 == res.code) {
                that.getInfo()
                that.getList(false);
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          });
        }
      }
    })
  },
  
  
  //审核消息全读
  readAllBindtapCheck:function (){
    var that = this;
    console.log(that.data.checkList)
    var changeData = that.data.checkList
    var readArray = []
    for (let i = 0; i < changeData.length; i++) {
      if (changeData[i].isRead == 0) {
        readArray = readArray.concat([changeData[i].id])
      }
    }
    app.req({
      url: "wechat/sysMessage/update",
      method: "post",
      data: {
        ids: readArray
      },
      success: function (res) {
        if (200 == res.code) {
          that.getInfo()
          for (let i = 0; i < readArray.length; i++) {
            var data = that.data;
            var flag = data.flag;
            that.toggle("flag.check", flag.check - 1);
            that.toggle("checkList[" + i + "].isRead", 1);
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },


  //系统消息全读
  readAllBindtapSystem: function () {
    var that = this;
    app.req({
      url: "wechat/sysMessage/updateByType",
      method: "post",
      data: {
        type:1
      },
      success: function (res) {
        if (200 == res.code) {
          that.getInfo()
          that.getList(false);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  touchS(e) {
    // 获得起始坐标
    this.startX = e.touches[0].clientX;
    this.startY = e.touches[0].clientY;
  },
  touchM(e) {
    var index = e.currentTarget.dataset.index
    // 获得当前坐标
    this.currentX = e.touches[0].clientX;
    this.currentY = e.touches[0].clientY;
    const x = this.startX - this.currentX; //横向移动距离
    const y = Math.abs(this.startY - this.currentY); //纵向移动距离，若向左移动有点倾斜也可以接受
    if (x > 35 && y < 110) {
      //向左滑是显示删除
      this.setData({
        status: index
      })
    } else if (x < -35 && y < 110) {
      //向右滑
      this.setData({
        status: null
      })
    }
  },
  del(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    console.log('删除id', id)
    wx.showModal({
      content: '是否要将此项删除',
      cancelColor: '#999999',
      confirmColor: '#2168EB',
      success(res) {
        if (res.confirm) {
          app.req({
            url: "wechat/sysMessage/deleteOne",
            method: "post",
            data: {
              id: id
            },
            success: function (res) {
              that.setData({
                status: null,
                pageNumber: 1,
              })
              that.getList(false);
            }
          });
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    app.getUserInfo(function (userInfo) {
      that.setData({
        user: userInfo
      });
    });
    that.getList(true);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.setNavigationBarTitle({
      title: '我的消息'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.toggle("status", null);
    this.toggle("pageNumber", 1);
    this.toggle("totalPages", 1);
    this.getList(false);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    var data = that.data;
    if (data.totalPages * 1 > data.pageNumber * 1) {
      that.toggle("pageNumber", data.pageNumber * 1 + 1);
      that.getList(true);
    }
  },
})